<?php

namespace common\base;

use peng\enums\DBOperator;

/**
 * 业务逻辑层-基类
 *
 * @author peng.huang
 */
abstract class BaseBiz {

    /**
     * 数据库访问类
     * 
     * @var type 
     */
    public $dao;

    /**
     * 数据访问类集合
     * 
     * @var array 
     */
    protected static $_daos = array();

    /**
     * 返回dao对象
     * 
     * @param string $className [类名]
     * @param string $db [数据库]
     * @param boolean $isNew [是否创建新的]
     * @return object
     */
    public static function getDao($className, $db = 'default', $isNew = FALSE) {
        $arguments = func_get_args();
        $args = array_slice($arguments, 3); // 移出$className、$db、$isNew
        if ($isNew) {
            return static::_createClass($className, $args);
        }

        // 单例
        $key = $db . str_replace('\'', '_', $className);
        if (!isset(static::$_daos[$key])) {
            static::$_daos[$key] = static::_createClass($className, $args);
        }

        return static::$_daos[$key];
    }

    /**
     * 创建类
     * 
     * @param string $className [类名]
     * @param array $arguments [参数]
     * @return object
     */
    protected static function _createClass($className, $arguments) {
        $class = new \ReflectionClass($className);
        return $class->newInstanceArgs($arguments);
    }

    /**
     * 返回需要保存的数据
     * 
     * @param object $entity [实体对象]
     * @return array
     */
    public function getSavedData($entity) {
        $data = get_object_vars($entity);
        unset($data['operator'], $data['timestamp'], $data['key'], $data['token']); /* 移除多余字段 */

        // 新增则移除自增ID
        if (isset($entity->operator) && DBOperator::INSERT === $entity->operator) {
            unset($data['id']);
        }

        return $data;
    }

    /**
     * 判断账号和令牌是否正确
     * 
     * @param object $entity [实体对象]
     * @return boolean
     */
    public function isUserTokenValid($entity) {
        if (!$this->checkTokenValid($entity)) {
            return FALSE;
        }

        $userBiz = new \common\biz\UserBiz();
        if (!isset($entity->userid) || !$userBiz->isExists($entity->userid)) {
            return $entity->appendError('userid', '该用户不存在。');
        }

        return TRUE;
    }

}
